import React, { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { connect } from 'react-redux'
import { CrossDomain } from '@/utils/cross-domain'
// 引入 WebView 组件
import { WebView, View } from '@tarojs/components'
import { carInfo } from '@/store/car/action'

const domain: string = `${BASE_H5_URL}/#`
type State = {
  webUrl: string,
  currentCar: any
}
type paramsData = {
  carId: string
  accessId: string
  accessKey: string
  storeCode: String
  serverTime: number
	cityCode:String
	areaCode:String
}
@connect<any>(({ car, maintain }) => ({ car, maintain }), _dispatch => ({
  dispatchCarInfo() {
    return _dispatch(carInfo())
  }
}))
class AppWebView extends Component<any, State> {
  $instance = getCurrentInstance();


  constructor(props) {
    super(props)
    this.state = {
      webUrl: '',
      currentCar: {}
    }
  }
  UNSAFE_componentWillMount() {
    let { query, path, ...rest } = this.$instance.router.params
    const arr = this.jsonToString({ ...rest })
    let authInfo: any = Taro.getStorageSync('IS_USERINFO')
    let herf = this.setHref(path, query)
    if (!this.props.car.carInfo.currentCar) {
      Taro.showLoading({ title: '拉取车型数据中' })
      this.props.dispatchCarInfo().then(() => {
        let data: paramsData = {
          carId: this.props.car.carInfo.currentCar ? this.props.car.carInfo.currentCar.id : '',
          accessId: authInfo.accessId,
          accessKey: authInfo.accessKey,
          storeCode: Taro.getStorageSync('STORECODE'),
          serverTime: authInfo.serverTime,
					cityCode: Taro.getStorageSync('CURRENT_LOCATION_INFO') ? Taro.getStorageSync('CURRENT_LOCATION_INFO').adCode : '',
          areaCode: Taro.getStorageSync('CURRENT_LOCATION_INFO') ? Taro.getStorageSync('CURRENT_LOCATION_INFO').districtCode : ''
        }
        let url = new CrossDomain({
          url: herf,
          data: data
        }).init()
        if (arr) {
          url = `${url}&${arr}`
        }
        this.setState({
          webUrl: url
        })
        Taro.hideLoading()
      })
    } else {
      let data: paramsData = {
        carId: this.props.car.carInfo.currentCar ? this.props.car.carInfo.currentCar.id : '',
        accessId: authInfo.accessId,
        accessKey: authInfo.accessKey,
        storeCode: Taro.getStorageSync('STORECODE'),
        serverTime: authInfo.serverTime,
				cityCode: Taro.getStorageSync('CURRENT_LOCATION_INFO') ? Taro.getStorageSync('CURRENT_LOCATION_INFO').adCode : '',
        areaCode: Taro.getStorageSync('CURRENT_LOCATION_INFO') ? Taro.getStorageSync('CURRENT_LOCATION_INFO').districtCode : ''
      }
      let url = new CrossDomain({
        url: herf,
        data: data
      }).init()
      if (arr) {
        url = `${url}&${arr}`
      }
      this.setState({
        webUrl: url,
        currentCar: this.props.car.carInfo.currentCar
      })
    }
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    // this.UNSAFE_componentWillMount()
    let currentCar = nextProps.car.carInfo.currentCar
    if (currentCar && currentCar.carLicense !== this.state.currentCar.carLicense) {
      let { query, path, ...rest } = this.$instance.router.params
      const arr = this.jsonToString({ ...rest })
      let authInfo: any = Taro.getStorageSync('IS_USERINFO')
      let herf = this.setHref(path, query)

      let data: paramsData = {
        carId: currentCar ? currentCar.id : '',
        accessId: authInfo.accessId,
        accessKey: authInfo.accessKey,
        storeCode: Taro.getStorageSync('STORECODE'),
        serverTime: authInfo.serverTime,
				cityCode: Taro.getStorageSync('CURRENT_LOCATION_INFO') ? Taro.getStorageSync('CURRENT_LOCATION_INFO').adCode : '',
        areaCode: Taro.getStorageSync('CURRENT_LOCATION_INFO') ? Taro.getStorageSync('CURRENT_LOCATION_INFO').districtCode : ''
      }
      let url = new CrossDomain({
        url: herf,
        data: data
      }).init()
      if (arr) {
        url = `${url}&${arr}`
      }
			console.log('webUrl',url)
      this.setState({
        webUrl: '',
      }, () => {
        setTimeout(() => {
          this.setState({
            webUrl: url,
            currentCar: currentCar ? currentCar : {}
          })
        }, 10)
      })
    }
    // Taro.startPullDownRefresh()
  }

  // 对象转url
  jsonToString(obj) {
    let arr = [];
    for (let key in obj) {
      arr.push(key + "=" + obj[key]);
    }
    return arr.join('&');
  }

  setHref(path, query: any) {
    path = path ? path : ''
    if (path && path.indexOf('http') !== 0) {
      path = `${domain}${path}`
    }
    return this.setUrlQuery({
      // url: `${domain}${path}`,
      url: path,
      query: query ? JSON.parse(query) : null
    })
  }
  setUrlQuery(options) {
    let { url, query } = options;
    if (!url) return '';
    if (query) {
      let queryArr: any = []
      for (const key in query) {
        if (query.hasOwnProperty(key)) {
          queryArr.push(`${key}=${query[key]}`)
        }
      }
      if (url.indexOf('?') !== -1) {
        url = `${url}&${queryArr.join('&')}`
      } else {
        url = `${url}?${queryArr.join('&')}`
      }
    }
    return url;
  }

  private query: object = {}
  handleMessage(e) {
    let { data } = e.detail
		console.log('会不会执行进来---------e',e)
    if (data) {
			if(process.env.TARO_ENV === 'weapp'){
				this.query = data[0]
			}else{
				console.log('data',data)
				this.query = data
			}
    }
  }

  // 是否点击确认上传图片
  componentWillUnmount() {
    Taro.setStorageSync('ANCARD_RETURN', JSON.stringify(this.query))
  }

  render() {

    const { webUrl } = this.state
    if (!webUrl) return
    console.log(webUrl)
    return (
      <View>
        {webUrl && <WebView src={webUrl} onMessage={this.handleMessage.bind(this)} />}
      </View>
    )
  }
}
export default AppWebView
